package com.xuanyue.db.xuan.antlr.v2.function;

import java.util.List;

import com.xuanyue.db.xuan.core.index.ListObject;
import com.xuanyue.db.xuan.core.table.IBitIndex;
import com.xuanyue.db.xuan.core.table.expr.Expr;
import com.xuanyue.db.xuan.core.table.expr.ExprValue;
import com.xuanyue.db.xuan.core.table.expr.ExprValueType;
import com.xuanyue.db.xuan.core.table.expr.IFunctionExecutor;

/**
 * 含有给定数组的其中一个元素
 *
 * @author 解观海
 * @email guanhaixie@sina.cn
 * @date 2021年1月21日
 *
 */
public class ListObjectHasOneFunction implements IFunctionExecutor<ListObject<?>> {

	@Override
	public void exprExe(ListObject<?> column, ExprValue v, List<IBitIndex> caches) {
		List<ExprValue> tar = v.getValue();
		Expr expr = new Expr();
		expr.setOp("=");
		IBitIndex r = caches.get(0);
		IBitIndex rTmp = caches.get(1);
		r.setAll(true);
		
		int[] indexs = new int[] {0,0,0};
		expr.setArryIndex(indexs);
		caches = caches.subList(1, caches.size());
		r.setAll(true);
		for(int i=0,s=tar.size(),l=column.getListSize();i<l;i++) {
			indexs[0]=i;
			for(int j=0;j<s;j++) {
				column.exe(expr, caches);
				r.or(rTmp);
			}
		}
	}

	@Override
	public int exprCheck(ListObject<?> column, ExprValue v) {
		if(!ExprValueType.ARRAY.is(v.getType())) {
			return 0;
		}
		List<ExprValue> tar = v.getValue();
		Expr expr = new Expr();
		expr.setOp("=");
		expr.setArryIndex(new int[] {0,0,0});
		int s=0;
		for(ExprValue ev:tar) {
			expr.setValue(ev);
			s = column.checkAndContSource(expr);
			if(s==0) {
				return 0;
			}
		}
		return s+1;
	}

}
